﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;
using iTunesLibrary.Music;
using System.Diagnostics;

namespace iTunesLibrary.Dal.Interop
{
    public class LibraryProvider : ILibraryProvider
    {
       private List<IITFileOrCDTrack> _tracks;
        
        private iTunesApp _itunes;
        private IITLibraryPlaylist _mainLibrary;
        public LibraryProvider()
        {
            _tracks = new List<IITFileOrCDTrack>();
            
        }

        public string Init()
        {
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "Init Start", EventLogEntryType.Information);
            _itunes = new iTunesApp();
            _mainLibrary = _itunes.LibraryPlaylist;
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "Init Stop", EventLogEntryType.Information);
            return _itunes.LibraryXMLPath;
        }

        public void Load()
        {
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "Load Start", EventLogEntryType.Information);
            
            IITTrackCollection tracks = _mainLibrary.Tracks;
            var myEnum = tracks.GetEnumerator();

            while (myEnum.MoveNext())
            {
                IITFileOrCDTrack currTrack = myEnum.Current as IITFileOrCDTrack;
                // is this a file track?
                if (currTrack != null && currTrack.Kind == ITTrackKind.ITTrackKindFile)
                {
                    _tracks.Add(currTrack);
                }
            }
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "Load Stop", EventLogEntryType.Information);
            
        }

        public bool UpdateName(Track track, string value)
        {
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "UpdateName Start", EventLogEntryType.Information);
            
            IITFileOrCDTrack trackToUpdate;
            if(!ValidateUpdate(track, out trackToUpdate))
                return false;
            trackToUpdate.Name = value;
            //EventLog.WriteEntry(this.GetType().Assembly.FullName, this.GetType().Name + "UpdateName Stop", EventLogEntryType.Information);
            
            return true;
        }

        private bool ValidateUpdate(Track track, out IITFileOrCDTrack trackToUpdate)
        {
            trackToUpdate = null;
            if (track == null)
                return false;
            System.Web.HttpUtility.UrlEncode(track.Location);
            trackToUpdate = _tracks.FirstOrDefault(x => x.Location == track.Location);
            if (trackToUpdate == null)
                return false;
            
            return true;
        }
    }
}
